package oktx.feign.terminator;

import oktx.participant.JtaParticipant;
import oktx.participant.Participant;
import oktx.RemoteType;
import oktx.terminator.Terminator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.client.RestTemplate;

/**
 * Created by huangdachao on 2018/5/30 15:33.
 */
public class RestTxTerminator implements Terminator {
    private static final Logger LOG = LoggerFactory.getLogger(RestTxTerminator.class);
    private RestTemplate restTemplate;

    public RestTxTerminator(RestTemplate template) {
        this.restTemplate = template;
    }

    @Override
    public void commit(Participant p) {
        try {
            restTemplate.headForHeaders("http://" + p.getIp() + ":" + p.getPort() + "/tx/commit?xid=" + p.getXid());
            LOG.debug("提交远程事务：" + p);
        } catch (Exception e) {
            LOG.error("提交远程事务失败：" + p, e);
        }
    }

    @Override
    public void rollback(Participant p) {
        try {
            restTemplate.headForHeaders("http://" + p.getIp() + ":" + p.getPort() + "/tx/rollback?xid=" + p.getXid());
            LOG.debug("回滚远程事务：" + p);
        } catch (Exception e) {
            LOG.error("回滚远程事务失败：" + p, e);
        }
    }

    @Override
    public boolean support(Participant p) {
        return p instanceof JtaParticipant && p.getType() == RemoteType.rest;
    }
}
